<!--交易组合管理-->
<template>
  <div class="app-container flex-cloumn">
    <el-form :model="queryParams" :rules="rules" ref="tradeProfitQueryRef" label-width="68px">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="组合" prop="groupId">
            <baseCombox url="/pricing/group/queryVGroupCombox.action"
                        clearable
                        :style="{width: '100%'}"
                        @change="handleInQuery"
                        valueField="dict_val"
                        labelField="dict_disp"
                        size="small" placeholder="组合" v-model="queryParams.groupId"></baseCombox>
          </el-form-item>
        </el-col>


        <el-col :span="6">
          <el-form-item label="合约编号" prop="iCode">
            <el-input
                v-model="queryParams.iCode"
                placeholder="请输入合约编号"
                clearable
                :style="{width: '100%'}"
                size="small"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="起始日">
            <el-date-picker
                v-model="queryParams.begDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.begDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="标的代码" prop="underlyerIds">
            <baseCombox url="/marketdata/instrument/getInstruments.action" clearable
                        size="small"
                        multiple collapse-tags collapse-tags-tooltip
                        valueField="code"
                        labelField="productName" placeholder="标的代码"
                        v-model="queryParams.underlyerIds"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="交易对手" prop="partyIds">
            <baseCombox url="/trade/counterparty/queryCounterparty4Combox.action" clearable multiple collapse-tags collapse-tags-tooltip
                        size="small" :style="{width: '100%'}"
                        v-model="queryParams.partyIds" labelField="partyName" placeholder="交易对手"
                        valueField="partyId"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="到期日">
            <el-date-picker
                v-model="queryParams.endDate1"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="-">
            <el-date-picker
                v-model="queryParams.endDate2"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="12">
        <el-col :span="6">
          <el-form-item label="本方账户" prop="accIds">
            <baseCombox url="/trade/account/querySelfAccountCombox.action" clearable multiple collapse-tags collapse-tags-tooltip
                        size="small" :style="{width: '100%'}"
                        valueField="accId" labelField="accName" placeholder="本方账户"
                        v-model="queryParams.accIds"></baseCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="期权类型">
            <dictCombox v-model="queryParams.optionTypes" :style="{width: '100%'}" dictType="optionType" multiple collapse-tags collapse-tags-tooltip
                        size="small"></dictCombox>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="交易类型">
            <dictCombox v-model="queryParams.tradeTypes"
                        multiple="true" collapse-tags collapse-tags-tooltip
                        filterKey="OtcOptionSell,OtcOptionBuy,LongOpen,LongClose,ShortOpen,ShortClose"
                        dictType="tradeType" size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="买卖方向" prop="payDirection">
            <dictCombox v-model="queryParams.payDirection" dictType="payDirection" size="small"></dictCombox>
          </el-form-item>
        </el-col>
        <el-col :span="8">
            <el-button type="primary" :loading="inloading" icon="Search"
                       size="small"
                       style="margin: 3px 3px"
                       v-hasPermi="['risk:profitmanage:tradeprofit:list']"
                       @click="handleInQuery">搜索
            </el-button>
            <el-button
                type="danger"
                style="margin: 3px 3px"
                icon="Delete"
                :loading="inloading"
                size="small"
                :disabled="multiple"
                @click="removeInGroup"
                v-hasPermi="['risk:profitmanage:tradeprofit:edt']"
            >移除
            </el-button>
            <el-button
                type="primary"
                style="margin: 3px 3px"
                icon="Plus"
                size="small"
                :loading="inloading"
                :disabled="btnFlag"
                @click="handleAdd"
                v-hasPermi="['risk:profitmanage:tradeprofit:add']"
            >分配
            </el-button>
        </el-col>
      </el-row>
    </el-form>


    <xTable v-loading="inloading" :data="inTradeProfitList" multiple="true" refId="refInGroupTable"
            ref="refInGroupTable" @selection-change="handleInSelectionChange" class="tableDragger_form"
    >
      <template #columList>
        <el-table-column label="序号" type="index" width="50">
        </el-table-column>
        <el-table-column label="本方账户" align="center" prop="accName" width="150"/>
        <el-table-column label="合约编号" align="center" prop="iCode" :formatter="formartICode" width="220"/>
        <el-table-column label="accId" align="center" prop="accId" v-if="false" width="150"/>
        <el-table-column align="center" label="交易对手" prop="partyName" width="100"/>
        <el-table-column label="交易类型" align="center" prop="tradeType" :formatter="formartTradeType" width="100"/>
        <el-table-column label="期权类型" align="center" prop="productType" width="120">
          <template #default="scope">
            <dict-tag :options="optionType" :value="scope.row.productType"/>
          </template>
        </el-table-column>
        <el-table-column label="标的代码" align="center" prop="uICode" width="100"/>
        <el-table-column label="标的名称" align="center" prop="uIName" width="200"/>
        <el-table-column label="起始日" align="center" prop="issueDate" width="100"/>
        <el-table-column label="到期日" align="center" prop="maturityDate" width="100"/>
        <el-table-column label="名义本金" align="right" prop="volume" :formatter="formartEmptyTableP2" width="150"/>
        <el-table-column label="费用" align="right" prop="fee" :formatter="formartEmptyTableP2" width="150"/>
<!--        <el-table-column label="保证金" align="right" prop="margin" :formatter="formartEmptyTableP2" width="150"/>-->
      </template>
    </xTable>
    <pagination
        style="margin:20px 0 20px 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getInGroupList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="tradeProfitOpen" width="80%" :close-on-click-modal="false"
               @opened="handleOutQuery" draggable="true" append-to-body>
      <div class="app-container flex-cloumn">
        <el-form :model="outQueryParams" :rules="rules" ref="tradeOutProfitQueryRef" label-width="68px">
          <el-row :gutter="12">
            <el-col :span="6">
              <el-form-item label="组合" prop="groupId">
                <baseCombox url="/pricing/group/queryVGroupCombox.action"
                            :style="{width: '100%'}"
                            clearable
                            @change="handleOutQuery"
                            :disabled="true"
                            valueField="dict_val"
                            labelField="dict_disp"
                            size="small" placeholder="组合" v-model="outQueryParams.groupId"></baseCombox>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="合约编号" prop="iCode">
                <el-input
                    v-model="outQueryParams.iCode"
                    :style="{width: '100%'}"
                    placeholder="请输入合约编号"
                    clearable
                    size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="起始日">
                <el-date-picker
                    v-model="outQueryParams.begDate1"
                    type="date"
                    :style="{width: '100%'}"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="-">
                <el-date-picker
                    v-model="outQueryParams.begDate2"
                    type="date"
                    :style="{width: '100%'}"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="12">
            <el-col :span="6">
              <el-form-item label="标的代码" prop="underlyerIds">
                <baseCombox url="/marketdata/instrument/getInstruments.action" clearable
                            size="small"
                            multiple collapse-tags collapse-tags-tooltip
                            valueField="code"
                            labelField="productName" placeholder="标的代码"
                            v-model="outQueryParams.underlyerIds"></baseCombox>

              </el-form-item>
            </el-col>


            <el-col :span="6">
              <el-form-item label="交易对手" prop="partyIds">
                <baseCombox url="/trade/counterparty/queryCounterparty4Combox.action" clearable multiple
                            size="small" collapse-tags collapse-tags-tooltip
                            :style="{width: '100%'}"
                            v-model="outQueryParams.partyIds" labelField="partyName" placeholder="交易对手"
                            valueField="partyId"></baseCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到期日">
                <el-date-picker
                    v-model="outQueryParams.endDate1"
                    type="date"
                    :style="{width: '100%'}"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="-">
                <el-date-picker
                    v-model="outQueryParams.endDate2"
                    type="date"
                    :style="{width: '100%'}"
                    value-format="YYYY-MM-DD"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="12">

            <el-col :span="6">
              <el-form-item label="本方账户" prop="accIds">
                <baseCombox url="/trade/account/querySelfAccountCombox.action" clearable multiple collapse-tags collapse-tags-tooltip
                            size="small"
                            :style="{width: '100%'}"
                            valueField="accId" labelField="accName" placeholder="本方账户"
                            v-model="outQueryParams.accIds"></baseCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="期权类型">
                <dictCombox v-model="outQueryParams.optionTypes" :style="{width: '100%'}" dictType="optionType" multiple
                            collapse-tags collapse-tags-tooltip    size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="交易类型">
                <dictCombox v-model="outQueryParams.tradeTypes"
                            multiple="true" collapse-tags collapse-tags-tooltip
                            :style="{width: '100%'}"
                            filterKey="OtcOptionSell,OtcOptionBuy,LongOpen,LongClose,ShortOpen,ShortClose"
                            dictType="tradeType" size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="买卖方向" >
                <dictCombox v-model="outQueryParams.payDirection" dictType="payDirection" size="small"></dictCombox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" :loading="outloading" icon="Search" size="small"
                           style="margin: 3px 3px"
                           v-hasPermi="['risk:profitmanage:tradeprofit:list']"
                           @click="handleOutQuery">搜索
                </el-button>
                <el-button type="success" :loading="outloading" icon="Plus" size="small"
                           style="margin: 3px 3px"
                           v-hasPermi="['risk:profitmanage:tradeprofit:add']"
                           @click="addInGroup">添加
                </el-button>
                <el-button type="warning" :loading="outloading" icon="Close" size="small"
                           style="margin: 3px 3px"
                           v-hasPermi="['risk:profitmanage:tradeprofit:cancel']"
                           @click="closeOutDialog">取消
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>


       <el-row>
         <xTable height="300px" v-loading="outloading" :data="outTradeProfitList" multiple="true" class="tableDragger_form"
                 refId="refOutGroupTable" ref="refOutGroupTable" @selection-change="handleOutSelectionChange"
         >
           <template #columList>
             <el-table-column label="序号" type="index" width="50">
             </el-table-column>
             <el-table-column label="本方账户" align="center" prop="accName" width="150"/>
             <el-table-column label="合约编号" align="center" prop="iCode" :formatter="formartICode" width="220"/>
             <el-table-column label="accId" align="center" prop="accId" v-if="false" width="150"/>
             <el-table-column align="center" label="交易对手" prop="partyName" width="100"/>
             <el-table-column label="交易类型" align="center" prop="tradeType" :formatter="formartTradeType" width="100"/>
             <el-table-column label="期权类型" align="center" prop="productType" width="120">
               <template #default="scope">
                 <dict-tag :options="optionType" :value="scope.row.productType"/>
               </template>
             </el-table-column>
             <el-table-column label="标的代码" align="center" prop="uICode" width="100"/>
             <el-table-column label="标的名称" align="center" prop="uIName" width="200"/>
             <el-table-column label="起始日" align="center" prop="issueDate" width="100"/>
             <el-table-column label="到期日" align="center" prop="maturityDate" width="100"/>
             <el-table-column label="名义本金" align="right" prop="volume" :formatter="formartEmptyTableP2" width="150"/>
             <el-table-column label="费用" align="right" prop="fee" :formatter="formartEmptyTableP2" width="150"/>
             <el-table-column label="保证金" align="right" prop="margin" :formatter="formartEmptyTableP2" width="150"/>
           </template>
         </xTable>
       </el-row>
         <el-row>
         <pagination
             style="margin:20px 0 20px 0"
             :total="outTotal"
             v-model:page="outQueryParams.pageNum"
             v-model:limit="outQueryParams.pageSize"
             @pagination="getOutGroupList"
         />
       </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Tradeprofit">
import xTable from "../../../../xquant/base/xTable";
import {
  getTradeProfitList,
  addTradeProfit,
  uptTradeProfit,
  delTradeProfit,
  getGroupBalance,
  removeToGroup,
  insertToGroup
} from "@/api/risk/profitmanage/tradeprofit";
import baseCombox from "../../../../xquant/base/baseCombox";
import dictCombox from "../../../../xquant/base/dictCombox"
import underlyer from "../../../../xquant/base/underlyer";
import {isVoid, isNotVoid} from "@/utils/util";

import Number from "../../../../xquant/base/number";
import {ref, watch} from "vue";

const {proxy} = getCurrentInstance();
const inTradeProfitList = ref([]);
const outTradeProfitList = ref([]);
const tradeProfitOpen = ref(false);
const loading = ref(false);
const inloading = ref(false);
const outloading = ref(false);
const selectObj = ref([]);
const selectOutObj = ref([]);
const multiple = ref(true);
const total = ref(0);
const outTotal = ref(0);
const title = ref("");
const btnFlag = ref(true);
const screenHeight = ref(document.documentElement.clientHeight - 300 + 'px')
const {tradeType, optionType} = proxy.useDict("tradeType", "optionType");
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    optionTypes: undefined,
    partyIds: undefined,
    accIds: undefined,
    iCode: undefined,
    underlyerIds: undefined,
    inGroup: true,
    containZeroBalance: false,
    groupId: undefined,
    groupType: 'in',
    tradeTypes: undefined,
    begDate1: undefined,
    begDate2: undefined,
    endDate1: undefined,
    endDate2: undefined,
    payDirection:undefined
  },
  outQueryParams: {
    pageNum: 1,
    pageSize: 10,
    optionTypes: undefined,
    partyIds: undefined,
    accIds: undefined,
    iCode: undefined,
    tradeTypes: undefined,
    underlyerIds: undefined,
    inGroup: false,
    containZeroBalance: false,
    groupId: undefined,
    groupType: 'out',
    payDirection:undefined
  },
  rules: {
    groupId: [{message: "组合不能为空", required: true, trigger: "blur"}]
  }

});
const {queryParams, outQueryParams, form, rules} = toRefs(data);

watch(() => queryParams.value.begDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.begDate2)
    if (a > b) {
      queryParams.value.begDate2 = newVal;
    }
  }
})
watch(() => queryParams.value.begDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.begDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.begDate1)
    if (a > b) {
      queryParams.value.begDate1 = newVal;
    }
  }
})
watch(() => queryParams.value.endDate1, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate2)) {
    let a = proxy.$moment(newVal)
    let b = proxy.$moment(queryParams.value.endDate2)
    if (a > b) {
      queryParams.value.endDate2 = newVal;
    }
  }
})
watch(() => queryParams.value.endDate2, (newVal, oldVal) => {
  if (isNotVoid(newVal) && isNotVoid(queryParams.value.endDate1)) {
    let b = proxy.$moment(newVal)
    let a = proxy.$moment(queryParams.value.endDate1)
    if (a > b) {
      queryParams.value.endDate1 = newVal;
    }
  }
})

/** 新增按钮操作 */
function handleAdd() {
  reset();
  outQueryParams.value.groupId = queryParams.value.groupId;
  outTradeProfitList.value = [];
  outTotal.value = 0;
  tradeProfitOpen.value = true;
  title.value = "分配交易";
}

function reset() {
  outQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    optionType: undefined,
    partyId: undefined,
    accId: undefined,
    iCode: undefined,
    underlyerId: undefined,
    inGroup: false,
    containZeroBalance: false,
    groupId: undefined,
    groupType: 'out'
  }
}

/** 取消按钮 */
function closeOutDialog() {
  tradeProfitOpen.value = false;
}

/** 查询组合内和组合外  搜索按钮方法 */
function handleInQuery() {
  queryParams.value.pageNum = 1;
  btnFlag.value = true;
  proxy.$refs["tradeProfitQueryRef"].validate(valid => {
    if (valid) {
      btnFlag.value = false;
      getInGroupList();
    } else {
      inTradeProfitList.value = [];
    }
  });
}

/** 查询组合内和组合外  搜索按钮方法 */
function handleOutQuery() {
  outQueryParams.value.pageNum = 1;
  proxy.$refs["tradeOutProfitQueryRef"].validate(valid => {
    if (valid) {
      getOutGroupList();
    } else {
      outTradeProfitList.value = [];
    }
  });
}

/** 组合内交易查询 */
function getInGroupList() {
  inloading.value = true;
  let qryParam = proxy.lsh.cloneDeep(queryParams.value);
  qryParam.groupType = 'in';
  qryParam.inGroup = true;
  qryParam.pageSize = queryParams.value.pageSize;
  qryParam.pageNum = queryParams.value.pageNum;
  qryParam.tradeTypes = proxy.lsh.join(qryParam.tradeTypes, ',');
  qryParam.accIds = proxy.lsh.join(qryParam.accIds, ',');
  qryParam.partyIds = proxy.lsh.join(qryParam.partyIds, ',');
  qryParam.underlyerIds = proxy.lsh.join(qryParam.underlyerIds, '|');
  qryParam.optionTypes = proxy.lsh.join(qryParam.optionTypes, ',');
  getGroupBalance(qryParam).then(response => {
    inTradeProfitList.value = response.list;
    total.value = response.total;
    inloading.value = false;
    selectObj.value = [];
  });
}

/** 组合外交易 */
function getOutGroupList() {
  outloading.value = true;
  let qryParam = proxy.lsh.cloneDeep(outQueryParams.value);
  qryParam.groupType = 'out';
  qryParam.inGroup = false;
  qryParam.pageSize = qryParam.pageSize;
  qryParam.pageNum = qryParam.pageNum;
  qryParam.tradeTypes = proxy.lsh.join(qryParam.tradeTypes, ',');
  qryParam.accIds = proxy.lsh.join(qryParam.accIds, ',');
  qryParam.partyIds = proxy.lsh.join(qryParam.partyIds, ',');
  qryParam.underlyerIds = proxy.lsh.join(qryParam.underlyerIds, '|');
  qryParam.optionTypes = proxy.lsh.join(qryParam.optionTypes, ',');
  getGroupBalance(qryParam).then(response => {
    outTradeProfitList.value = response.list;
    outTotal.value = response.total;
    outloading.value = false;
    selectOutObj.value = [];
  });
}

//交易类型翻译
function formartTradeType(row, column, cellValue) {
  let fmtValue = '*';
  proxy.lsh.map(tradeType.value, function (o) {
    if (o.value == cellValue) {
      fmtValue = o.label;
    }
  });
  return fmtValue;
}

//合约编号翻译
function formartICode(row, column, cellValue) {
  let fmtValue = cellValue;
  if (row.productType == '' || row.productType == null || row.productType == undefined) {
    fmtValue = '*';
  }
  return fmtValue;
}

function addInGroup() {
  if (selectOutObj.value.length > 0) {
    insertToGroup({'data': JSON.stringify(selectOutObj.value)}).then(response => {
      handleOutQuery();
      handleInQuery();
    });
  } else {
    proxy.$modal.alertWarning("请选择一条交易!");
  }
}

function removeInGroup() {
  if (selectObj.value.length > 0) {
    removeToGroup({'data': JSON.stringify(selectObj.value)}).then(response => {
      handleInQuery();
    });
  } else {
    proxy.$modal.alertWarning("请选择组合内的交易!");
  }
}

/**=========table组件行选中 */

/** 多选框选中数据 */
function handleInSelectionChange(selection) {
  selectObj.value = selection.map(item => {
    return {
      'accId': item.accId,
      'tradeId': item.tradeId,
      'iCode': item.iCode,
      'aType': item.aType,
      'mType': item.mType,
      'groupId': queryParams.value.groupId
    };
  });
  multiple.value = !selection.length;
}

/** 多选框选中数据 */
function handleOutSelectionChange(selection) {
  selectOutObj.value = selection.map(item => {
    return {
      'accId': item.accId,
      'tradeId': item.tradeId,
      'iCode': item.iCode,
      'aType': item.aType,
      'mType': item.mType,
      'groupId': outQueryParams.value.groupId
    };
  });
}
onMounted(() => {
  setTimeout(() => {
    inloading.value = false
  }, 300)
  window.onresize = function temp() {
    screenHeight.value = document.documentElement.clientHeight - 300 + 'px;'
  }
})
</script>
